package com.hmdp.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

@Slf4j
@Component
public class RedisClient {

    private StringRedisTemplate stringRedisTemplate;

    public RedisClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }


    //这里需要声明一个线程池，因为下面我们需要新建一个现成来完成重构缓存
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 缓存普通对象
     * @param key
     * @param value
     * @param time
     * @param unit
     */
    public void set(String key, Object value,Long time, TimeUnit unit){
        String jsonStr = JSONUtil.toJsonStr(value);
        stringRedisTemplate.opsForValue().set(key,jsonStr,time,unit);
    }

    /**
     * 缓存逻辑过期对象
     * @param key
     * @param value
     * @param time
     * @param unit
     */
    public void setLogicalExpire(String key,Object value,Long time, TimeUnit unit){
        //设置逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));

        //写入redis
        String jsonStr = JSONUtil.toJsonStr(redisData);
        stringRedisTemplate.opsForValue().set(key,jsonStr,time,unit);
    }


    /**
     * 缓存穿透
     * @param prefix
     * @param id
     * @param type
     * @param dbFallback
     * @param time
     * @param unit
     * @param <R>
     * @param <ID>
     * @return
     */
    public <R,ID> R getShopByIdWithCachePenetrate(String prefix, ID id, Class<R> type, Function<ID,R> dbFallback,Long time, TimeUnit unit) {

        String key = prefix + id;

        //1.根据商铺id查询redis缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        //2.判断缓存是否存在
        if(StrUtil.isNotBlank(shopJson)){
            //3.存在，直接返回
            return JSONUtil.toBean(shopJson, type);
        }

        //如果查询到的是空字符串，说明是我们缓存的空数据
        if (shopJson != null){
            return null;
        }

        //4.不存在，根据id查询数据库
        R r = dbFallback.apply(id);

        if(r == null){
            //5.不存在，缓存空字符串
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }

        //6.存在，写入redis
       this.set(key, r,time, unit);

        //7.返回商铺信息
        return r;
    }

    /**
     * 缓存击穿--逻辑过期
     * 因为不存在就会返回空，所以要做好缓存预热
     * @param
     * @return
     */
    public <R,ID> R getShopByIdWithCacheBreakdown2(String profix, ID id,Class<R> type, Function<ID,R> dbFallback,Long time, TimeUnit unit) {

        String key = profix + id;

        //1.根据id查询redis缓存
        String Json = stringRedisTemplate.opsForValue().get(key);

        //2.判断缓存是否存在
        if (StrUtil.isBlank(Json)) {
            //3.未命中，直接返回null
            return null;
        }

        //4.命中
        //4.1将json反序列化为对象
        RedisData redisData = JSONUtil.toBean(Json, RedisData.class);
        //4.2将data转为type对象
        JSONObject json = (JSONObject) redisData.getData();
        R r = JSONUtil.toBean(json, type);
        //4.3获取过期时间
        LocalDateTime expireTime = redisData.getExpireTime();
        //4.4判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())){
            //5.未过期，返回商铺信息
            return r;
        }
        //6 过期，获取互斥锁，开启独立线程 缓存重建
        //6.1尝试获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        Boolean isLock = tryLock(lockKey);
        if (isLock){
            //6.2获取锁成功，开启独立线程，实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    //查询数据
                    R r1 = dbFallback.apply(id);
                    //写入redsi
                    this.setLogicalExpire(key,r1,time,unit);
                }catch (Exception e){
                    throw new RuntimeException(e);
                }finally {
                    //6.3释放锁
                    unLock(lockKey);
                }
            });
            //7.直接返回商铺信息
            return r;
        }
        //8.未获取到锁，直接返回商铺信息
        return r;
    }

    /**
     * 加锁
     */
    public Boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(flag);
    }

    /**
     * 释放锁
     */
    public void unLock(String key){
        stringRedisTemplate.delete(key);
    }


}
